const { default: axios } = require('axios');
const { Controller } = require('egg');

class UserController extends Controller {
  async login() {
    const { ctx } = this;
    const { userInfo, code } = ctx.request.body;
    console.log('[userInfo]', userInfo);
    console.log('[code]', code);
    // const detail = await ctx.service.beerRecord.add({ name: 'test' });
    const resp = await axios.get(
      'https://api.weixin.qq.com/sns/jscode2session',
      {
        params: {
          js_code: code,
          appid: 'wx960ee1261ca18903',
          secret: '792dc2c8c0775563e4a340d93610da07',
          grant_type: 'authorization_code',
        },
      }
    );
    const hadUser = await ctx.service.user.detail({
      open_id: resp.data.openid,
    });
    if (!hadUser) {
      await ctx.service.user.add({
        open_id: resp.data.openid,
        nick_name: userInfo.nickName || 'beerMaster_' + new Date(),
        ava_url: userInfo.avatarUrl,
        create_time: new Date(),
      });
    }

    const token = ctx.app.jwt.sign(
      {
        open_id: resp.data.openid,
      },
      this.app.config.jwt.secret,
      {
        expiresIn: '600m', // 时间根据自己定，具体可参考jsonwebtoken插件官方说明
      }
    );

    ctx.body = {
      code: 0,
      data: { token },
    };
  }

  async detail() {
    const { ctx } = this;

    const token = ctx.request.header.authorization.replace('Bearer ', '');
    // 解码token
    const { open_id } = ctx.app.jwt.verify(token, 'beermaster');

    const detail = await ctx.service.user.detail({ open_id });
    ctx.body = {
      code: 0,
      data: detail,
    };
  }

  // async add() {
  //   const { ctx } = this;
  //   const { body } = ctx.request;
  //   console.log('[body]', body);
  //   const detail = await ctx.service.beerRecord.add(body);
  //   ctx.body = {
  //     code: 0,
  //     data: detail,
  //   };
  // }
}

module.exports = UserController;
